package main;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.lsc.context.StrategyContext;

public class Menu {
	
	private static Scanner sc = new Scanner(System.in);     //获取控制台输出对象
	private static Map<String,String> strategy = new HashMap<String,String>();
	
	/**
	 * 菜单目录
	 */
	public void menu(){
		boolean flog = false;
		do{
			flog=printConsole();
		}while(flog);
	}
	

	
	
	/**
	 * 控制台菜单输出
	 * @return boolean
	 */
	private boolean printConsole(){
		System.out.println("\n\n\n===========商店金额优惠系统=========");
		for(String id:strategy.keySet()){
			System.out.print(id+strategy.get(id)+"\n");
		}
		System.out.println("请选择优惠方式：\n");
		String fs = sc.nextLine();
		System.out.println("请输入结账金额：\n");
		double money = Double.parseDouble(sc.nextLine());
		if(strategy.get(fs)!=null){
			getResult(strategy.get(fs),money);
		}else{
			System.out.println("优惠方式不存在！\n");
		}
		System.out.println("\n\n======================我是分割线====================");
		System.out.println("\n是否继续？y/n");
		String exit = sc.nextLine();
		if(exit.equalsIgnoreCase("y")){
			return true;
		}
		return false;
	}
	
	/**
	 * 传入优惠方式和金额，输出结算金额
	 * @param strategy
	 * @param money
	 */
	private void getResult(String strategy,double money){
		StrategyContext context = new StrategyContext(strategy);
		context.getResult(money);
	}
	
	
	/**
	 * 静态块：获取优惠目录集合
	 */
	static {
		try {   
				     File file = new File(StrategyContext.xmlPath);   
				    SAXReader reader = new SAXReader();   
				     Document doc =  reader.read(file);   
				     Element root = doc.getRootElement();
				  
				    for (Iterator i = root.elementIterator("strategy"); i.hasNext();) {   
				        Element foo = (Element) i.next();
						strategy.put(foo.elementText("id"), foo.elementText("name"));
				    }
			  } catch (Exception e) {   
				  System.err.println("error：该配置文件不存在，请将项目下Strategy.xml放置在硬盘指定位置，并修改StrategyContext的xmlPath为其绝对地址！！！");
					e.printStackTrace();
			  }   
		
	}
	
}
